//
//  UIWindow+Extension.swift
//  fruit-helper-swift
//
//  Created by 赵隆杰 on 2022/6/14.
//

import Foundation
import UIKit

extension UIWindow {
    
    func currentViewController() -> UIViewController? {
        if let window: UIWindow = currentWindow() {
            var topViewcontroller = window.rootViewController
            
            while (topViewcontroller?.presentedViewController != nil)  {
                topViewcontroller = topViewcontroller?.presentedViewController
            }
            if let tabbar = topViewcontroller as? UITabBarController, tabbar.selectedViewController != nil {
                topViewcontroller = tabbar.selectedViewController
            }
            while let navi = topViewcontroller as? UINavigationController, navi.topViewController != nil  {
                topViewcontroller = navi.topViewController
            }
            return topViewcontroller
        }
        return nil
    }
    
    /// 获取当前window
    func currentWindow() -> UIWindow? {
        if #available(iOS 14.0, *) {
            if let window = UIApplication.shared.connectedScenes.map({$0 as? UIWindowScene}).compactMap({$0}).first?.windows.first {
                return window
            } else if let window = UIApplication.shared.delegate?.window {
                return window
            } else {
                return nil
            }
        } else if #available(iOS 13.0, *) {
            if let window = UIApplication.shared.connectedScenes.filter({$0.activationState == .foregroundActive}).map({$0 as? UIWindowScene}).compactMap({$0}).first?.windows.filter({$0.isKeyWindow}).first {
                return window
            } else if let window = UIApplication.shared.delegate?.window {
                return window
            } else {
                return nil
            }
        } else {
            if let window = UIApplication.shared.delegate?.window {
                return window
            } else {
                return nil
            }
        }
    }
    
}


